package com.example.pceb.minIO;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class MinioService {

    private final MinioClient minioClient;
    private final MinioConfig config;

    public String upload(MultipartFile file) {
        try {
            String filename = UUID.randomUUID() + "-" + file.getOriginalFilename();
            InputStream stream = file.getInputStream();

            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(config.getBucketName())
                    .object(filename)
                    .stream(stream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(args);

            // 拼接公开访问地址
            return config.getEndpoint() + "/" + config.getBucketName() + "/" + filename;
        } catch (Exception e) {
            throw new RuntimeException("上传失败：" + e.getMessage());
        }
    }
}
